import React from 'react'
import { connect } from 'react-redux'
import BraftEditor from 'braft-editor'
import UploadFile from 'components/upload'
import { messages } from 'share/common'
import { Button, Modal, Icon, message } from 'antd';
import docService from 'containers/help-center-user/doc/doc.service'
import config from 'config'

class EditDoc extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fileUploadVisible: false,
      content: null
    }
  }

  componentWillMount(){

  }

  //上传文件
  handleFileUpload = (fileList) => {
    let content = this.state.content;
    fileList.map(item => {
      content += `<a href="${item.response.fileURL}" target="">${item.response.fileName}</a>`;
    });
    this.editorInstance.setContent(content, 'html');
    this.handleContentChange(content);
    this.setState({ fileUploadVisible: false })
  };

  handleContentChange = (content) => {
    this.setState({ content })
  };

  //富文本中上传图片
  handleImageUpload = (param) => {
    const formData = new FormData();
    formData.append('attachmentType', 'CARROUSEL_IMAGES');
    formData.append('file', param.file);
    docService.handleImageUpload(formData).then(res => {
      param.success({ url: res.data.fileURL })
    }).catch(e => {
      param.error();
      message.error(`${messages('doc.key1'/*图片上传失败*/)}，${e.response.data.message}`)
    })
  };

  render(){
    const { fileUploadVisible, content } = this.state;
    const controls = [
      'undo', 'redo', 'split', 'text-align', 'font-size', 'font-family', 'line-height', 'text-color',
      'bold', 'italic', 'underline', 'strike-through', 'superscript',
      'subscript', 'split', 'headings', 'list_ul', 'list_ol',
      'blockquote', 'code', 'split', 'link', 'split', 'media', 'clear'
    ];
    const extendControls = [{
      type: 'button',
      text: <Icon type="file-add" />,
      hoverTitle: messages('doc.key2'/*上传文件*/),
      className: 'file-add',
      onClick: () => this.setState({ fileUploadVisible: true })
    }];
    return (
      <div style={{ height: '100%' }}>

        <BraftEditor height="100%"
                     controls={controls}
                     language={this.props.language.locale}
                     contentFormat="html"
                     initialContent={content}
                     extendControls={extendControls}
                     media={{
                       image: true,
                       video: false,
                       audio: false,
                       externalMedias: {
                         image: false,
                         video: false,
                         audio: false
                       },
                       uploadFn: this.handleImageUpload
                     }}
                     ref={instance => this.editorInstance = instance}
                     onChange={this.handleContentChange}/>

        {fileUploadVisible && (
          <Modal title={messages('doc.key2'/*上传文件*/)}
                 visible={fileUploadVisible}
                 footer={
                   <Button onClick={() => this.setState({ fileUploadVisible: false })}>
                     {messages('common.cancel')}
                   </Button>
                 }
                 onCancel={() => this.setState({ fileUploadVisible: false })}
          >
            <UploadFile uploadUrl={`${config.baseUrl}/api/upload/static/attachment`}
                        attachmentType="OTHER"
                        fileNum={1}
                        needAllResponse={true}
                        uploadHandle={this.handleFileUpload}/>
          </Modal>
        )}
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    language: state.main.language,
  }
}

export default connect(mapStateToProps)(EditDoc);
